package com.zyt.demo.foundation;

import java.util.ArrayList;
import java.util.Arrays;

public class StringDemo {
    public static void main(String[] args) {
        stringDemo();
    }

    public static void stringDemo() {
        // 初始化和构造
        // 字面量语法
        String str = "Hello World";
        System.out.println("Str = " + str);//Hello World

        // char数组初始化
        char chars[] = {'a', 'b', 'c'};
        str = new String(chars);
        System.out.println("Str = " + str);//abc

        // byte数组初始化
        char bytes[] = {65, 66, 67, 68};
        str = new String(bytes);
        System.out.println("Str = " + str);//ABCD

        // 获取长度判断是否为空
        System.out.println("length = " + str.length());//4
        System.out.println("isEmpty = " + str.isEmpty());//false
        System.out.println("isEmpty = " + "".isEmpty());//true

        // 比较，根据ascii码比较
        System.out.println("compare result = " + str.compareTo("BC"));//-1
        System.out.println("compare result = " + str.compareTo("AA"));//1
        System.out.println("compare result = " + str.compareTo("ABC"));//0

        // 判断是否有前缀
        System.out.println("startsWith result = " + str.startsWith("BC"));//false
        System.out.println("startsWith result = " + str.startsWith("AB"));//true

        // 查找
        System.out.println("indexOf result = " + str.indexOf("B"));//1
        System.out.println("indexOf result = " + str.indexOf("BC"));//1
        System.out.println("indexOf result = " + str.indexOf("F"));//-1

        // 子字符串获取
        System.out.println("substring result = " + str.substring(1));//BCD
        System.out.println("substring result = " + str.substring(1, 3));//BC
        // System.out.println("substring result = " + str.substring(1, 6));// error:StringIndexOutOfBoundsException
        // System.out.println("substring result = " + str.substring(6));// error:StringIndexOutOfBoundsException

        // 转小写
        System.out.println("toLowerCase result = " + str.toLowerCase());//abcd

        // 去空白
        String containBlankString = " ABCDEF ";
        System.out.println("toLowerCase result = " + containBlankString.trim());//ABCDEF

        // 字符分割以及数组拼接为字符串
        str = "AA|BB|CC|DD|EE";
        String[] splitResult = str.split("\\|");
        System.out.println("split result = " + Arrays.asList(splitResult));// [AA, BB, CC, DD, EE]
        System.out.println("join result = " + String.join("-", splitResult));// AA-BB-CC-DD-EE
    }
}
